<script setup lang="tsx">
import Write from './components/Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { computed, onMounted, reactive, ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRoute, useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { FormSchema } from '@/components/Form'
import {
  ElButton,
  ElCheckboxGroup,
  ElCheckbox,
  ElInput,
  ElRadio,
  ElRadioGroup,
  ElTag,
  ElMessage,
  ElDatePicker
} from 'element-plus'
import { OrderType } from '@/api/check/order/types'
import { Table, TableColumn } from '@/components/Table'
import { Uploader } from '@/components/AttactmentUploader'
import { Dialog } from '@/components/Dialog'
import {
  addOrderApi,
  addOrderContentApi,
  addOrderProgressApi,
  getOrderApi,
  putOrderApi,
  putOrderStampApi,
  putOrderStatusApi,
  deleteOrderContentApi
} from '@/api/check/order'
import Rebut from '@/views/Check/Rebut/Rebut.vue'
import { getFileName } from '@/utils'

const { emit } = useEventBus()

const { push, go } = useRouter()
const route = useRoute()

const { t } = useI18n()

const currentRow = ref<OrderType>()

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <div class="flex w-full">
              <div class="w-50">
                <span>SAMC 05-3(2019-12)</span>
                <br />
                <span>
                  状态: <ElTag>{currentRow.value?.status || '未创建'}</ElTag>
                </span>
              </div>
              <div class="font-bold text-xl text-center w-full">
                <span>工艺控制实验室报告</span>
                <br />
                <span>PROCESS CONTROL LABORATORY REPORT</span>
              </div>
              <div class="w-50 block">
                <ElButton link onClick={() => rebutAction('detail')}>
                  查看驳回历史
                </ElButton>
                <br />
                <ElButton link onClick={() => progressAction('detail')}>
                  查看进度说明
                </ElButton>
                <br />
              </div>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'order_type',
    label: '试验类型:',
    colProps: {
      span: 8
    }
  },
  {
    field: 'order_no',
    label: '试验编号:',
    colProps: {
      span: 8
    }
  },
  {
    field: 'qar_no',
    label: 'QAR编号:',
    colProps: {
      span: 8
    }
  },
  {
    field: 'test_type',
    label: '实验分类',
    colProps: {
      span: 18
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              {data.test_type
                ? data.test_type.split(';').map((item) => <ElTag class="ml-10">{item}</ElTag>)
                : ''}
            </>
          )
        }
      }
    }
  },
  {
    field: 'test_type_button',
    colProps: {
      span: 6
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <ElButton onClick={() => (dialogVisible.value = true)}>点击添加</ElButton>
            </>
          )
        }
      }
    }
  },
  {
    field: 'received_by',
    label: '收料人',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: (data) =>
          data.received_by ? (
            <>{data.received_by}</>
          ) : (
            <ElButton onClick={() => updateStamp(data, 'received_by')}>刷卡</ElButton>
          )
      }
    }
  },
  {
    field: 'feeded_by',
    label: '送料人',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: (data) =>
          data.feeded_by ? (
            <>{data.feeded_by}</>
          ) : (
            <ElButton onClick={() => updateStamp(data, 'feeded_by')}>刷卡</ElButton>
          )
      }
    }
  },
  {
    field: '',
    colProps: {
      span: 24
    }
  },
  {
    field: 'prepared_by',
    label: '1.编制者:\nPREPARED BY',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: (data) =>
          data.prepared_by ? (
            <>{data.prepared_by}</>
          ) : (
            <ElButton onClick={() => updateStamp(data, 'prepared_by')}>刷卡</ElButton>
          )
      }
    }
  },
  {
    field: 'prepared_date',
    label: '日期:\nDATE',
    colProps: {
      span: 12
    }
    // component: 'DatePicker',
    // componentProps: {
    //   type: 'datetime',
    //   valueFormat: 'YYYY-MM-DD HH:mm:ss'
    // }
  },
  {
    field: 'prepared_dept',
    label: '部门:\nDEPT',
    colProps: {
      span: 12
    }
    // component: 'Input'
  },
  {
    field: 'prepared_phone',
    label: '电话:\nPHONE',
    colProps: {
      span: 12
    },
    component: 'Input'
  },
  {
    field: 'material_description',
    label: '2.材料说明:\nMATERIAL\nDESCRIPTION',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea'
    }
    // component: 'Input'
  },
  {
    field: 'vendor',
    label: '3.卖主:\nVENDOR BY',
    colProps: {
      span: 12
    },
    component: 'Input'
  },
  {
    field: 'po',
    label: '订单:\nP.O.',
    colProps: {
      span: 12
    }
  },
  {
    field: 'test_document',
    label: '4.试验文件:\nTEST DOCUMENT',
    colProps: {
      span: 12
    },
    component: 'Input'
  },
  {
    field: 'lot_size',
    label: '批量:\nLOT SIZE',
    colProps: {
      span: 12
    },
    component: 'Input'
  },
  {
    field: '',
    colProps: {
      span: 24
    }
  },
  {
    field: '',
    label: '5.实验结果:\nTEST RESULT',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <ElButton onClick={() => (resultVisible.value = true)}>添加实验结果</ElButton>
              <ElButton onClick={() => progressAction('add')}>添加进度说明</ElButton>
            </>
          )
        }
      }
    }
  },
  {
    field: '',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <div class="flex ml-10">
              <ElCheckbox v-model={data.is_urgent} label="是否加急" />
              <ElCheckbox v-model={data.is_heavy_urgent} label="是否特急" />
              <span class="flex ml-10">
                <span class="mr-2">需求完成时间:</span>
                <ElDatePicker
                  v-model={data.require_finish_datetime}
                  type="datetime"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: '',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          const tableColumns = reactive<TableColumn[]>([
            {
              field: 'index',
              label: '序号',
              minWidth: 80,
              slots: {
                default: (scope) => <>{scope.$index + 1}</>
              }
            },
            {
              field: 'test_name',
              label: '实验名称',
              minWidth: 120
            },
            {
              field: 'attachment',
              label: '附件',
              minWidth: 120,
              slots: {
                default: (scope) => (
                  <a href={scope.row.attachment} target="_blank">
                    {getFileName(scope.row.attachment)}
                  </a>
                )
              }
            },
            {
              field: 'is_pass',
              label: '符合规范要求',
              minWidth: 90,
              slots: {
                default: (scope) => (
                  <ElRadioGroup modelValue={scope.row.is_pass}>
                    <ElRadio value={true}>是</ElRadio>
                    <ElRadio value={false}>否</ElRadio>
                  </ElRadioGroup>
                )
              }
            },
            {
              field: 'test_performed_by',
              label: '实验员',
              minWidth: 120
              // slots: {
              //   default: (scope) => <ElInput v-model={scope.row.test_performed_by} />
              // }
            },
            {
              field: 'operation',
              label: '操作',
              minWidth: 120
              // slots: {
              //   default: (scope) => <ElInput v-model={scope.row.operation} />
              // }
            },
            {
              field: 'action',
              label: '',
              slots: {
                default: (data) => (
                  <ElButton link onClick={() => deleteOrderContent(data.row)}>
                    删除
                  </ElButton>
                )
              }
            }
          ])
          return <Table data={data.contents} columns={tableColumns} class="w-full" />
        }
      }
    }
  },
  {
    field: '',
    colProps: {
      span: 24
    }
  },
  {
    field: 'approved_by',
    label: '9.批准:\nAPPROVED',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: (data) =>
          data.approved_by ? (
            <>{data.approved_by}</>
          ) : (
            <ElButton onClick={() => updateStamp(data, 'approved_by')}>刷卡</ElButton>
          )
      }
    }
  },
  {
    field: 'meet_spec_requirements',
    label: '符合规范要求',
    colProps: {
      span: 12
    },
    component: 'Input'
  }
])

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    loading.value = true
    try {
      if (currentRow.value?.id) {
        const res = await putOrderApi({ ...formData, id: currentRow.value.id })
        if (res) refresh()
      } else {
        const res = await addOrderApi({ ...formData })
        if (res) refresh(res.data)
      }
    } finally {
      loading.value = false
    }
  }
}

const updateStamp = async (row, type) => {
  const res = await putOrderStampApi(row.id ?? currentRow.value?.id, { type })
  if (res) refresh()
}

// const addItem = () => {
//   currentRow.value?.contents?.push({
//     test_name: '',
//     attachment: '',
//     is_pass: undefined,
//     test_performed_by: '',
//     operation: ''
//   })
//   console.log(currentRow)
// }

// const deleteItem = (index: number) => {
//   currentRow.value?.contents?.splice(index, 1)
// }
const deleteOrderContent = async (row) => {
  const res = await deleteOrderContentApi(row.order_id, [row.id])
  if (res) {
    ElMessage.success('删除实验结果成功')
    refresh()
  }
}

const saveLoading = ref(false)

// 添加实验分类
const dialogVisible = ref(false)
const testTypes = ref<string[]>([])

const handleUpdateTestType = async () => {
  if (!currentRow.value?.id) {
    ElMessage.warning('未创建的委托单不允许添加实验')
    return
  }
  const res = await putOrderApi({ id: currentRow.value?.id, test_type: testTypes.value.join(';') })
  if (res) {
    currentRow.value = res.data
    dialogVisible.value = false
  }
}

// 添加实验结果
const resultForms = reactive<FormSchema[]>([
  {
    field: 'test_name',
    label: '实验名称',
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'attachment',
    label: '附件',
    component: 'Input',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => <Uploader v-model={data.attachment} />
      }
    }
  },
  {
    field: 'is_pass',
    label: '符合规范要求',
    component: 'Select',
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ]
    }
  },
  {
    field: 'operation',
    label: '操作',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea'
    }
  }
])
const resultVisible = ref(false)
const saveResult = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res = await addOrderContentApi({
        ...formData,
        order_id: currentRow.value?.id,
        status: currentRow.value?.status
      })
      if (res) refresh()
    } finally {
      saveLoading.value = false
      resultVisible.value = false
    }
  }
}

// 进度说明
const progressVisible = ref(false)
const progressActionType = ref()
const progressTitle = ref()
const progressColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index'
  },
  {
    field: 'content',
    label: '进度说明',
    minWidth: 120
  },
  {
    field: 'status',
    label: '添加进度时状态',
    minWidth: 120
  }
])
const progressForms = reactive<FormSchema[]>([
  {
    field: 'content',
    label: '进度说明',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea'
    }
  }
])
const progressAction = (action: string) => {
  if (action == 'add') {
    progressActionType.value = 'add'
    progressTitle.value = '添加进度说明'
  } else {
    progressActionType.value = 'detail'
    progressTitle.value = '查看进度说明'
  }
  progressVisible.value = true
}

const saveProgress = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res = await addOrderProgressApi({
        ...formData,
        order_id: currentRow.value?.id,
        status: currentRow.value?.status
      })
      if (res) refresh()
    } finally {
      saveLoading.value = false
      progressVisible.value = false
    }
  }
}

// 驳回历史
const rebutVisible = ref(false)
const rebutActionType = ref()
const rebutParams = ref()
const rebutAction = (action: string) => {
  rebutVisible.value = true
  rebutActionType.value = action
  rebutParams.value =
    action === 'add'
      ? {
          rebut_type: currentRow.value?.order_type,
          rebut_form_no: currentRow.value?.order_no,
          before_status: currentRow.value?.status
        }
      : {
          rebut_type: currentRow.value?.order_type,
          rebut_form_no: currentRow.value?.order_no
        }
}

// 刷新表单
const refresh = async (data: any | undefined = undefined) => {
  const id = data?.id || currentRow.value?.id
  if (id) {
    const res = await getOrderApi({ id })
    if (res) currentRow.value = res.data
    if (currentRow.value?.test_type) testTypes.value = currentRow.value.test_type.split(';')
  }
}

// 更新状态
const updateStatus = async (status: string | undefined = undefined) => {
  const res = await putOrderStatusApi({ id: currentRow.value?.id, status })
  if (res) refresh()
}

// 初始化，获取详情
onMounted(async () => {
  const params = {
    ...route.params,
    ...route.query
  }
  refresh(params)
})

// 监听驳回
useEventBus({
  name: 'addRebut',
  callback: () => {
    refresh()
  }
})
</script>

<template>
  <ContentDetailWrap>
    <Write ref="writeRef" :form-schema="schema" :current-row="currentRow" class="form-container" />

    <template #header>
      <ElButton @click="go(-1)">
        {{ t('common.back') }}
      </ElButton>
      <ElButton v-if="['实验中', '计划中'].includes(currentRow?.status ?? '')" @click="save">
        保存修改
      </ElButton>
      <ElButton v-if="currentRow?.status == '计划中'" @click="updateStatus()"> 收料完成 </ElButton>
      <ElButton v-if="currentRow?.status == '实验中'" @click="updateStatus('等待其他实验')">
        等待其他实验
      </ElButton>
      <ElButton v-if="currentRow?.status == '实验中'" @click="updateStatus()"> 提交审核 </ElButton>
      <!-- <ElButton v-if="currentRow?.status == '实验中'" @click="updateStatus()">
        提交加工
      </ElButton> -->
      <ElButton v-if="currentRow?.status == '审核中'" @click="updateStatus()"> 审核完成 </ElButton>
      <ElButton
        @click="rebutAction('add')"
        v-if="['实验中', '审核中'].includes(currentRow?.status ?? '')"
      >
        驳回
      </ElButton>
      <!-- <ElButton>打印</ElButton> -->
    </template>
  </ContentDetailWrap>

  <Dialog v-model="dialogVisible" title="实验分类" width="700px" max-height="100px">
    <ElCheckboxGroup v-model="testTypes">
      <ElCheckbox label="机性实验" value="机性实验" />
      <ElCheckbox label="金相实验" value="金相实验" />
      <ElCheckbox label="化学实验" value="化学实验" />
      <ElCheckbox label="非金属实验" value="非金属实验" />
      <ElCheckbox label="断裂韧性实验" value="断裂韧性实验" />
    </ElCheckboxGroup>
    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="handleUpdateTestType">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
  <Dialog v-model="progressVisible" :title="progressTitle" width="800px" max-height="300px">
    <Write v-if="progressActionType == 'add'" ref="writeRef" :form-schema="progressForms" />
    <Table
      v-if="progressActionType == 'detail'"
      :data="currentRow?.progresses"
      :columns="progressColumns"
      class="w-full"
    />
    <template #footer>
      <ElButton
        v-if="progressActionType == 'add'"
        type="primary"
        :loading="saveLoading"
        @click="saveProgress"
      >
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="progressVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
  <Dialog v-model="resultVisible" title="添加实验结果" width="800px" max-height="300px">
    <Write ref="writeRef" :form-schema="resultForms" />
    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="saveResult">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="resultVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
  <Rebut v-model="rebutVisible" :action="rebutActionType" :params="rebutParams" />
</template>
<style lang="less" scoped>
.form-container {
  border: 3px solid #909399;
  :deep(.el-row) {
    .el-col:first-child {
      border-bottom: 2px solid #909399;
    }
    .el-col:not(:first-child) {
      border: 1px solid #909399;
    }
  }
  :deep(.el-form-item) {
    margin: 18px 0;
    align-items: center;
  }
  :deep(.el-form-item__label) {
    font-size: 13px;
    line-height: 15px !important;
    align-items: center;
    text-align: right;
    white-space: pre-line !important;
  }
  :deep(.el-table .cell) {
    white-space: pre-wrap !important;
    text-align: center;
    font-size: 13px;
  }
}
</style>
@/hooks/event/useEventBus
